//
//  NRWCarPushMsgModel.m
//  New_Runway
//
//  Created by NewLife on 2018/2/24.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarPushMsgModel.h"
#import "NSString+StringForTime.h"
#import "NSString+FilePath.h"

@interface NRWCarPushMsgModel()<NSCoding>
@end

NSString *keyStr = @"123";

@implementation NRWCarPushMsgModel

+ (void)addNewModelWithUserInfo:(NSDictionary *)userInfo {
    
    NSDictionary *messageBody = userInfo[@"aps"];
    
    if (messageBody == nil) {
        return;
    }
    
    NRWCarPushMsgModel *model = [[NRWCarPushMsgModel alloc] init];
    model.alert = messageBody[@"alert"];
    if (isEmptyOrNilString(userInfo[@"title"])) {
        model.title = @"启辕汽车";
    } else {
        model.title = userInfo[@"title"];
    }
    model.timeStr = [NSString getTimeWithYYYY_MM_dd_HH_mm];
    
    saveNewModelIntoCache(model);
}

+ (void)getCacheModelArrCompleted:(void(^)(NSArray <NRWCarPushMsgModel *>* modelArr))completed {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        NSArray *obj = getOldModelArr();
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            if (completed) {
                completed(obj);
            }
        });
    });
}

NSArray <NRWCarPushMsgModel *>*getOldModelArr() {
    
    return [NSKeyedUnarchiver unarchiveObjectWithFile:getCachePath()];
}

void saveNewModelIntoCache(NRWCarPushMsgModel *model) {
    
    NSMutableArray <NRWCarPushMsgModel *>*arrM = [NSMutableArray arrayWithArray:getOldModelArr()];
    
    if ([arrM.lastObject.alert isEqualToString:model.alert]) {//防止重复添加
        return;
    }
    
    [arrM insertObject:model atIndex:0];
    
    [NSKeyedArchiver archiveRootObject:arrM.copy toFile:getCachePath()];
}

NSString *getCachePath() {
    
    return [[NSString getCachesDir] stringByAppendingPathComponent:@"pushMessageCache.plist"];
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    
    [aCoder encodeObject:self.alert forKey:@"alert"];
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:self.timeStr forKey:@"timeStr"];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        
        self.alert = [aDecoder decodeObjectForKey:@"alert"];
        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.timeStr = [aDecoder decodeObjectForKey:@"timeStr"];
    }
    return self;
}

@end
